/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DataStructuresThreads;

import Sorting.Main;
import Sorting.ThreadAuxiliary;
import com.sun.j3d.utils.geometry.Box;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.media.j3d.BranchGroup;
import javax.media.j3d.Transform3D;
import javax.media.j3d.TransformGroup;
import javax.swing.*;
import javax.vecmath.Vector3f;

/**
 *
 * @author rafael
 */
public class QueueThread extends Thread {
    
    public static boolean isRunning = false;
    public QueueThread queueThread = this;
    public static Vector3f elementPosition = new Vector3f(-0.2f, 0.0f, -0.2f);

    public QueueThread(String name) {
        super(name);
    }

    @Override
    public void run() {
        execute();
    }

    private void execute() {
        
        try {
            Main.textPane.setText(Main.textoQueue);
            callQueueButtons();
            Main.frame.setEnabled(false);

            BranchGroup bgroup = Main.queueBranchGroup();
            Main.su.addBranchGraph(bgroup);

        } finally {
            Main.isRunning = false;
//            Main.clearTexts();
            Main.textPane.setText(Main.textoQueue);
            Main.textPane2.setText("tamanho = " + Main.queueSize + "\ncapacidade = " + Main.queueCapacity);
        }
    }
    
    private static void checkElementPosition() {
        
        elementPosition.x = (Main.queueSize * 0.3f) - 0.2f;
        
    }

    public static void insertElement() {
        
        Main.highlightsText("  se (tamanho == capacidade) {\n", Main.textoQueue);
        if (Main.queueSize == Main.queueCapacity) {
            Main.highlightsText("    Erro: Não há capacidade para mais elementos!\n", Main.textoQueue);
            JOptionPane.showMessageDialog(null, "Capacidade está no limite, não pode adicionar novos elementos.");
        
        } else {
            Main.highlightsText("  } senao {\n", Main.textoQueue);

        String numberString = "";
        int number = -1;

        while (number < 0 || number > 9) {
            numberString = JOptionPane.showInputDialog("Qual o número à ser adicionado?");
            
            if (numberString == null || numberString.equals("")) {    
            } else {
                number = Integer.parseInt(numberString);
            }
            
        }
        
        System.out.println("Vai adicionar o: " + number);
        
        BranchGroup branchGroup = new BranchGroup();

        Box listElement = new Box(0.1f, 0.2f, 0.15f, Main.criarApp());
        listElement.setCapability(Box.ENABLE_APPEARANCE_MODIFY);
        
        Transform3D tfBox = new Transform3D();
        
        checkElementPosition();
        
        tfBox.setTranslation(new Vector3f(elementPosition.x, elementPosition.y, elementPosition.z));
        
        TransformGroup tgBox = new TransformGroup(tfBox);
        tgBox.addChild(listElement);
        branchGroup.addChild(tgBox);
        
        Main.highlightsText("    fila[tamanho] = numero;\n", Main.textoQueue);
        
        
        Main.numberList.add(new Sorting.Number(number, tgBox, 0.1f));
        Main.su.addBranchGraph(branchGroup);
        
        Main.highlightsText("    tamanho++;\n", Main.textoQueue);
        Main.queueSize++;
        Main.textPane.getStyledDocument().setCharacterAttributes(0, Main.textoQueue.length(), Main.defaultText, true);
        Main.textPane2.setText("tamanho = " + Main.queueSize + "\ncapacidade = " + Main.queueCapacity);
        
        }
    }
    
    public static void popElement () {
        
        Main.highlightsText("  se(tamanho == 0) {\n", Main.textoQueue);
        if (Main.queueSize == 0) {
            Main.highlightsText("    Erro: Não há elementos à serem retirados!\n", Main.textoQueue);
            JOptionPane.showMessageDialog(null, "Fila vazia, não há elementos à serem retirados!");
            Main.textPane.getStyledDocument().setCharacterAttributes(0, Main.textoQueue.length(), Main.defaultText, true);
        
        } else {
        Main.highlightsText("  } senao  {\n", Main.textoQueue);
        
        Main.highlightsText("    fila[0] = null;\n", Main.textoQueue);
        Main.destroyListElement(0);
        
        Main.numberList.remove(0);
        Main.highlightsText("    tamanho--;\n", Main.textoQueue);
        Main.queueSize--;
        
        float x = -0.2f;
        
            for (int i = 0; i < Main.numberList.size(); i++) {
                Main.moveQueueObject(Main.numberList, i, x);
                x += 0.3f;
            }
            
//        elementPosition.x = Main.queueSize * 0.3f - 0.8f;
            checkElementPosition();
        
        
        }
        Main.textPane.getStyledDocument().setCharacterAttributes(0, Main.textoQueue.length(), Main.defaultText, true);
        Main.textPane2.setText("tamanho = " + Main.queueSize + "\ncapacidade = " + Main.queueCapacity);
    }
    
    public static void topElement () {
        
        Main.highlightsText("  se (tamanho == 0) {\n", Main.textoQueue);
        if (Main.numberList.isEmpty()) {
            Main.highlightsText("    Erro: Não há elementos na fila!\n", Main.textoQueue);
            JOptionPane.showMessageDialog(null, "Não há elementos na fila.");
            Main.textPane.getStyledDocument().setCharacterAttributes(0, Main.textoQueue.length(), Main.defaultText, true);
        } else {
            
            Main.highlightsText("  retorna fila[0];\n", Main.textoQueue);
            JOptionPane.showMessageDialog(null, "O elemento do topo da fila é: " + Main.numberList.get(0).getNumber());
        }
    }
    
    public static void showElements() {
        
        if (Main.numberList.isEmpty()) {
        
            JOptionPane.showMessageDialog(null, "Não há elementos na fila.");
            
        } else {
            
            
            String numeros = "{ ";
            
                for (int i = 0; i < Main.numberList.size(); i++) {
                    numeros += Main.numberList.get(i).getNumber() + " ";
                }
            numeros += "}";
            
            JOptionPane.showMessageDialog(null, "Elementos: " + numeros);
        
        }
        
    }

    public void callQueueButtons() {


        JFrame frame = new JFrame("Queue Actions");

        JPanel vectorButtonsPanel = new JPanel(new GridLayout(3, 0));

        JButton addButton = new JButton("Inserir");
        JButton removeButton = new JButton("Retirar");
        JButton lastElementButton = new JButton("Último Índice");
        JButton showElementsButton = new JButton("Queue Elements");

        addButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                Thread t = new ThreadAuxiliary(queueThread, 1);
                t.start();
            }
        });

        removeButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                Thread t = new ThreadAuxiliary(queueThread, 2);
                t.start();
            }
        });

        lastElementButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                Thread t = new ThreadAuxiliary(queueThread, 3);
                t.start();
            }
        });

        showElementsButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
               showElements(); 
            }
            
        });
        
        JLabel exitLabel = new JLabel("Para finalizar a execução do vetor, feche esta janela");
        JTextArea exitText = new JTextArea("Para finalizar a execução do vetor, feche esta janela");
        exitText.setEditable(false);
        exitText.setLineWrap(true);
        exitText.setAutoscrolls(true);
        vectorButtonsPanel.add(addButton);
        vectorButtonsPanel.add(removeButton);
        vectorButtonsPanel.add(lastElementButton);
//        vectorButtonsPanel.add(showElementsButton);
        frame.add(vectorButtonsPanel);
        frame.setBounds(415, 60, 300, 140);

        frame.addWindowListener(new WindowAdapter() {

            public void windowClosing(WindowEvent e) {
                    
                for (int i = 0; i < Main.numberList.size(); i++) {
                        Main.destroyQueueObject(Main.numberList, i);
                        
                }
                Main.queueSize = 0;
                Main.isRunning = false;
                Main.clearTexts();
                Main.frame.setEnabled(true);
                
            }
        });

        frame.setResizable(false);
        frame.setVisible(true);
        Main.textPane2.setText("tamanho = " + Main.queueSize + "\ncapacidade = " + Main.queueCapacity);
    }
}
